package cn.south.campus.common.exceptions;

import cn.south.campus.common.model.bo.Result;
import cn.south.campus.common.model.enums.CommonEnums;
import cn.south.campus.common.utils.LoggerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Objects;


/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2022/5/7 17:20
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result<Void> exceptionHandler(BusinessException e) {
        LoggerUtil.warn(logger, e, e.getTips());
        return Result.error(e.getCode(), e.getTips());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<Void> exceptionHandler(MethodArgumentNotValidException e) {
        LoggerUtil.warn(logger, e, e.getMessage());
        return Result.error(CommonEnums.PARAMS_ERROR.getCode(), Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public Result<Void> exceptionHandler(MaxUploadSizeExceededException e) {
        LoggerUtil.warn(logger, e, e.getMessage());
        return Result.error(CommonEnums.FILE_OUT_OF_SIZE_ERROR);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Void> exceptionHandler(Exception e) {
        LoggerUtil.error(logger, e, e.getMessage());
        return Result.error();
    }
}
